package com.ktvme.project;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ktvme.core.AbstractOperator;
import com.ktvme.core.DolphinException;
import com.ktvme.result.PageResult;
import com.ktvme.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

@Slf4j
public class ProjectOperator extends AbstractOperator {

    public ProjectOperator(String baseUrl, String token) {
        super(baseUrl, token);
    }
    public List<ProjectInfoResp> list(){
        String url = baseUrl + "/projects/list";
        try {
            String jsonString = HttpUtil.sendGetRequest(url, token);
            JSONObject jsonObject = JSON.parseObject(jsonString);
            JSONArray data = jsonObject.getJSONArray("data");
            List<ProjectInfoResp> javaList = data.toJavaList(ProjectInfoResp.class);
            return javaList;
        }catch (Exception e)
        {
            throw new DolphinException("获取项目列表失败",e);
        }

    }

    public PageResult<ProjectInfoResp> page(int page, int size) {
        String url = baseUrl + "/projects?pageNo=" + page + "&pageSize=" + size;
        try {
            log.info("url:" + url + ",token:" + token);
            String jsonString = HttpUtil.sendGetRequest(url, token);
            JSONObject jsonObject = JSON.parseObject(jsonString);

            if (jsonObject == null) {
                throw new DolphinException("响应数据为空");
            }

            log.info("page:" + jsonObject);
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray totalList = data.getJSONArray("totalList");

            if (data == null || data.isEmpty()) {
                throw new DolphinException("数据列表为空");
            }

            List<ProjectInfoResp> javaList = totalList.toJavaList(ProjectInfoResp.class);
            PageResult<ProjectInfoResp> listPageResult = new PageResult<>();
            listPageResult.setRecords(javaList);
            listPageResult.setCurrentPage(page);
            listPageResult.setPageSize(size);

            Integer totalPages = data.getInteger("totalPage");
            Integer totalRecord = data.getInteger("total");

            listPageResult.setTotalPages(totalPages);
            listPageResult.setTotalRecord(totalRecord);

            return listPageResult;
        } catch (Exception e) {
            throw new DolphinException("获取项目列表失败", e);
        }
    }

}
